<div class="article">
  <div class="article-top">
    <!-- 操作按钮 -->
    <div class="article-option">
      <button type="button" class="btn btn-primary" id="article-add">新增</button> 
      <button type="button" class="btn btn-danger" id="article-batch-del">批量删除</button>
    </div>
    <!-- 搜索栏 -->
    <div class="article-column">
      <!-- 日历 -->
      <div class="article-calendar">
        <span>选择日期：</span>
        <input type="text" id="datepicker" class="calendar-datepicker" placeholder="2020-01-01 ~ 2020-05-10">
        <i class="fa fa-calendar"></i>
      </div>
      <!-- 搜索框 -->
      <div class="article-search">
        <input type="text" class="search-tit" placeholder="请输入标题或作者">
        <i class="fa fa-search"></i>
        <!-- 搜索或重置按钮 -->
        <button type="button" class="btn btn-primary" id="article-seaBtn">搜索</button>
        <button type="button" class="btn btn-danger" id="article-reset">重置</button>
      </div>
    </div>
  </div>
  
  <div class="article-table">
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th>编号</th>
          <th>文章标题</th>
          <th>所属栏目</th>
          <th>作者</th>
          <th>发布时间</th>
          <th>阅读次数</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <!-- 追加文章数据 -->
      </tbody>
    </table>

    <!-- 分页序号 -->
    <nav aria-label="Page navigation">
      <ul class="pagination">
        <li>
          <a href="#" aria-label="Previous" class="paging">
            <span aria-hidden="true">&laquo;</span>
          </a>
        </li>
        <!-- <li><a href="#">1</a></li> -->
        <!-- <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li> -->
        <li id="paging-one"><a href="#">1</a></li>
        <li id="paging-two"><a href="#" class="paging">2</a></li>
        <li id="paging-three"><a href="#" class="paging">3</a></li>
        <li id="paging-four"><a href="#" class="paging">4</a></li>
        <li id="paging-five"><a href="#" class="paging">5</a></li>
        <li>
          <a href="#" aria-label="Next" class="paging">
            <span aria-hidden="true">&raquo;</span>
          </a>
        </li>
      </ul>
    </nav>
  </div>
  
  <!-- 模态框 -->
  <div class="modal fade" id="article-modal" tabindex="-1" role="dialog" aria-labelledby="article-modalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="article-modalLabel">添加咨询</h4>
        </div>
        <div class="modal-body">
          <!-- 表单 -->
          <form class="form-horizontal">
            <div class="form-group">
              <label for="article-name" class="col-sm-2 control-label">文章标题</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="article-name" placeholder="请输入文章标题">
              </div>
            </div>
            <div class="form-group">
              <label for="article-parent" class="col-sm-2 control-label">所属栏目</label>
              <div class="col-sm-10">
                <select id="article-parent" class="form-control">
                  <!-- 遍历一级栏目 -->
                </select>
              </div>
            </div>
            <div class="form-group">
              <label for="article-list" class="col-sm-2 control-label">列&nbsp;&nbsp;&nbsp;&nbsp;表<br>略缩图</label>
              <div class="col-sm-10">
                <button type="button" class="btn btn-info">点击上传</button>
              </div>
            </div>
            <div class="form-group">
              <label for="article-text" class="col-sm-2 control-label">正&nbsp;&nbsp;&nbsp;&nbsp;文</label>
              <div class="col-sm-10">
                <input type="text" class="form-control" id="article-written" placeholder="请输入正文描述">
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <button id="article-save" type="button" class="btn btn-primary">确定</button>
        </div>
      </div>
    </div>
  </div>

</div>

<script>
  //日历选择器jQuery插件
  $(function(){
    $( "#datepicker" ).datepicker();
  });
  
  //当前页面的所有文章数据
  var articleData = [];
  // 当前修改的文章栏目对象
  var currentArticle = {};
  
  //获取文章数据，遍历数据对象，追加节点
  function findArticle(test){
		$('.paging').css({color:'#000',backgroundColor:'#fff'});
		$(this).css({color:'#fff',backgroundColor:'#31b0d5'});
    $('#paging-one a').css({color:'#000',backgroundColor:'#fff'});
		if($(this).text() == '1'){
			test = 0;
		}else if($(this).text() == '2'){
			test = 1;
		}else if($(this).text() == '3'){
			test = 2;
		}else if($(this).text() == '4'){
			test = 3;
		}else if($(this).text() == '5'){
			test = 4;
		}else if($(this).attr('aria-label') == 'Previous'){  //如果点左按钮(上一个)，页数向上改变
			$('.paging').eq(0).css({color:'#000',backgroundColor:'#fff'});
			if(copyTest == 1 || copyTest == 0){
				test = 0;
				$('#paging-one a').css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 2){
				test = 1;
				$('.paging').eq(1).css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 3){
				test = 2;
				$('.paging').eq(2).css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 4){
				test = 3;
				$('.paging').eq(3).css({color:'#fff',backgroundColor:'#31b0d5'});
			}
		}else if($(this).attr('aria-label') == 'Next'){  //如果点右按钮(上一个)，页数向下改变
			$('.paging').eq(5).css({color:'#000',backgroundColor:'#fff'});
			if(copyTest == 4 || copyTest == 3){
				test = 4;
				$('.paging').eq(4).css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 2){
				test = 3;
				$('.paging').eq(3).css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 1){
				test = 2;
				$('.paging').eq(2).css({color:'#fff',backgroundColor:'#31b0d5'});
			}else if(copyTest == 0){
				test = 1;
				$('.paging').eq(1).css({color:'#fff',backgroundColor:'#31b0d5'});
			}
    }
    
    //每次运行函数前，清空tbody里的数据
    $('.article tbody').empty();
		myAjax('/manager/article/findArticle','get',{page:test,pageSize:11},function(res){
			//res.data.list当前页面的文章数据
			articleData = res.data.list;
			//console.log(articleData);
			//1.将数据显示在表格中
			res.data.list.forEach(function (item){
        // item指向每一个list对象
				var $tr = $(`<tr>
						<td>
							<input type="checkbox" value="`+item.id+`">
						</td>
						<th>`+ item.title +`</th>
						<th>`+ (item.category ? item.category.name : '---') +`</th>
						<th>`+ (item.author ? item.author.username : '---') +`</th>
						<th>`+ item.publishtime +`</th>
						<th>`+ item.readtimes +`</th>
						<th>`+ item.status +`</th>
						<td>
							<span class="article-delete">
								<i class="fa fa-trash-o" title="删除"></i>
							</span>
							<span class="article-edit">
								<i class="fa fa-pencil-square-o" title="修改"></i>
							</span>
						</td>
					</tr>`);
        $('.article tbody').append($tr);
      });
      
      //2.设置模态框中的父栏目遍历，清空下拉列表，追加option
      //res.data.list = [{},{},{}]    内部存放的是栏目对象
      //parent = [{},{},{}]   内部存放父栏目对象
      //过滤出当前页面的父栏目
      var parent = res.data.list.filter(function (item) {
        return item.category ? item.category.name : '---';
        //return item.category.name;  //如果有空对象，就返回undefined，页面产生断点
        //console.log(typeof item.category);  //object
        //console.log(item.category);
        //console.log(item.category.name);
      });
      $('#article-parent').empty();
      $('#article-parent').append('<option value="">请选择</option>');
      parent.forEach(function (item) {
        var $option = $('<option value="' + item.id + '">' + item.category.name + '</option>');
        //console.log($option);
        //console.log(item.category.name);
        $('#article-parent').append($option);
      });
		});
    copyTest = test;    
	}

  // 默认展示第一页的文章数据
	$('#paging-one').click( function(){
		findArticle(0);
		$('#paging-one a').css({color:'#fff',backgroundColor:'#31b0d5'});
	}).trigger('click');
	//点击换页 事件代理  
	$('.pagination').on('click','.paging',findArticle);
 
  //新增  设置模态框标题，清空内部表单内容，显示模态框
  $('#article-add').click(function () {
    currentArticle = {};
    //清空内部表单内容
    $('#article-name').val('');
    $('#article-parent').val('');
    $('#article-list').val('');
    $('#article-written').val('');
    //设置模态框标题
    $('#article-modalLabel').text('添加咨询');
    //显示模态框
    $('#article-modal').modal('show');
  });

  // 修改  事件代理   设置模态框标题，设置内部表单内容，显示模态框
  $('.article-table').on('click', '.article-edit', function () {
    var id = $(this).closest('tr').find('[type=checkbox]').val();
    // 通过id获取当前修改的对象，要去所有的栏目数组中进行过滤
    currentArticle = articleData.filter(function (item) {
      return item.id == id;
    })[0];
    //console.log(articleData);
		//console.log(currentArticle);
		//console.log(currentArticle.category.name);
    //将栏目对象中的数据设置到表单中
    $('#article-name').val(currentArticle.title);
    $('#article-parent').val(currentArticle.category ? currentArticle.category.name : '');  
    //$('#article-parent').val('');
    //$('#article-list').val(currentArticle.author.userface);
    $('#article-list').val('');
    //console.log(currentArticle.author.userface);
    $('#article-written').val(currentArticle.content);
    $('#article-modalLabel').text('修改咨询');
    $('#article-modal').modal('show');
  })

  //保存
  $('#article-save').click(function(){
    //获取表单数据
    var name = $('#article-name').val();
    var categoryId = $('#article-parent').val();
    var list = $('#article-list').val();
    var written = $('#article-written').val();
    //验证数据
    if(name && categoryId && written){
      //封装数据，保存
      var obj = {
        id: currentArticle.id,
				title: name,
				liststyle: 'true',
				content: written,
        categoryId: categoryId,  //199
        no: null,
        parentId: 1,
      };
      myAjax('/manager/article/saveOrUpdateArticle','post',obj,function(res){
				if(res.status == 200){
          findArticle(copyTest);
          alert('保存的数据在最后一页');
					// 模态框关闭
					$('#article-modal').modal('hide');
				}else{
          alert('保存失败');
					$('#article-modal').modal('hide');
				}
			})
    }else{
      alert('请输入文章标题和所属栏目')
    }
  })

  /* $('#article-save').click(function(){
    alert('保存出错啦，后台数据好像找不到了QvQ');
    $('#article-modal').modal('hide');
  }) */

  //单个删除
  $('.article-table').on('click', '.article-delete', function () {
    var id = $(this).closest('tr').find('[type=checkbox]').val();
    var result = confirm('是否确定删除？');
    if(result){
      myAjax('/manager/article/deleteArticleById','get',{ id:id },function(res){
        if(res.status == 200){
          alert('删除成功');        
          findArticle(copyTest);  
        }else{
          alert('删除失败，数据库的数据不可以删除哦！请删除作者为空的数据');
        }
      },function(err){
        alert('删除失败');
      })
    }
  })

  /* $('.article-table').on('click', '.article-delete', function () {
    var id = $(this).closest('tr').find('[type=checkbox]').val();
    var result = confirm('是否确定删除？');
    if(result){
      alert('删除失败');
    }    
  }); */

  //批量删除
  $('#article-batch-del').click(function(){
    //获取用户选中的复选框按钮的id，得到类数组
    var ids = $('.article-table :checkbox:checked').map(function (index, item) {
      return item.value;
    }).toArray();
    //console.log(ids);
    if(ids.length>0){
      var result = confirm('是否确定删除？');
      if(result){
        //如果选中多个复选框，那么进行批量删除
        myAjax('/manager/article/deleteArticleById','post',{ ids: ids.toString()},function(res){
          if(res.status == 200){
            findArticle(copyTest);
          }else{
            alert('批量删除失败！数据库的数据不可以删除哦~请删除作者为空的数据');
            // 清空用户选择的checkbox
            $('.article-table :checkbox:checked').prop('checked', false);
          }
        },function(err){
          alert('批量删除失败！数据库的数据不可以删除哦~请删除作者为空的数据');
          // 清空用户选择的checkbox
          $('.article-table :checkbox:checked').prop('checked', false);
        })
      }
    }else{
      alert('请勾选需要删除的数据');
    }
  })

  //搜索  *未实现输入关键字后，列表清空，追加搜索到的表格
  /* $('#article-seaBtn').click(function(){
    alert('请输入需要搜索的文字');
  })
  $('#article-seaBtn').click(function(){
		// 清空表单
		$('.article tbody').empty();
		// 拿到满足条件的数据再追加到表单上
		myAjax('/manager/article/findArticle','get',{},function(res){
			//  dates 满足条件的栏目对象数组
			var datas = res.data.map(function(item){
				return (item.title == $('.search-tit').val() || item.author.username == $('.search-tit').val());
			});
			// 遍历数组  将满足条件的对象一个一个追加到表单中
			datas.forEach(function(item){
				$('.article tbody').append(item);
			});
		})
	}); */

  //重置
  $('#article-reset').click(function(){
    //清空日历和搜索框的值
    $('#datepicker').val('');
    $('.search-tit').val('');
    var ids = $('.article-table :checkbox:checked').map(function (index, item) {
      return item.value;
    }).toArray();
    if(ids.length>0){
      //所有复选框清空
      $(".article-table :checkbox").each(function(){this.checked=false;});
    }else{
      alert('请勾选需要重置的数据');
    }
  })

</script>
